package com.atguigu.yygh.order.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.yygh.common.exception.YYGHException;
import com.atguigu.yygh.common.utils.HttpRequestSend;
import com.atguigu.yygh.enums.OrderStatusEnum;
import com.atguigu.yygh.hosp.client.ScheduleFeignClient;
import com.atguigu.yygh.model.order.OrderInfo;
import com.atguigu.yygh.model.user.Patient;
import com.atguigu.yygh.model.user.UserInfo;
import com.atguigu.yygh.mq.constant.MessageQueueContant;
import com.atguigu.yygh.order.OrderMainStarter;
import com.atguigu.yygh.order.mapper.OrderInfoMapper;
import com.atguigu.yygh.order.service.OrderInfoService;
import com.atguigu.yygh.user.client.PatientFeignClient;
import com.atguigu.yygh.vo.hosp.ScheduleOrderVo;
import com.atguigu.yygh.vo.msm.MsmVo;
import com.atguigu.yygh.vo.order.OrderMqVo;
import com.atguigu.yygh.vo.order.OrderQueryVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.joda.time.DateTime;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 * <p>
 * 订单表 服务实现类
 * </p>
 *
 * @author atguigu
 * @since 2023-03-30
 */
@Service
public class OrderInfoServiceImpl extends ServiceImpl<OrderInfoMapper, OrderInfo> implements OrderInfoService {

    @Autowired //注入scheduleFeignClient对象
    private ScheduleFeignClient scheduleFeignClient;
    @Autowired //注入patientFeignClient对象
    private PatientFeignClient patientFeignClient;
    @Autowired
    private RabbitTemplate rabbitTemplate; //注入rabbitTemplate对象
    @Override
    public Long submitOrdder(Long patientId, String scheduleId) {
        //1.获取就诊人信息
        Patient patient = patientFeignClient.patient(patientId);
        //2.根据排班id获取排班信息
        ScheduleOrderVo scheduleOrderVo = scheduleFeignClient.getRemoteScheduleById(scheduleId);
        DateTime stopTime = new DateTime(scheduleOrderVo.getStopTime());

        if(stopTime.isBeforeNow()){ //时间判断是不是在此时此刻之前
            throw new YYGHException(20001,"超过了当天挂号截止时间");
        }
        Map<String,Object> paramMap = new HashMap<String,Object>();
        paramMap.put("hoscode",scheduleOrderVo.getHoscode());
        paramMap.put("depcode",scheduleOrderVo.getDepcode());
        paramMap.put("hosScheduleId",scheduleOrderVo.getHosScheduleId());
        paramMap.put("reserveDate",scheduleOrderVo.getReserveDate());
        paramMap.put("reserveTime",scheduleOrderVo.getReserveTime());
        paramMap.put("amount",scheduleOrderVo.getAmount());

        //3.商易通预约挂号平台请求第三方医院
        JSONObject response = HttpRequestSend.sendRequest(paramMap,"http://localhost:9998/order/submitOrder");
        OrderInfo orderInfo = null;
        if(null != response && 200 == response.getIntValue("code")){
            orderInfo = new OrderInfo();
            //3.2第三方医院同意,继续走
            //3.2.1.把前面获得的3个数据添加到order_info
            orderInfo.setUserId(patient.getUserId());
            String outTradeNo = System.currentTimeMillis() + ""+ new Random().nextInt(100);
            orderInfo.setOutTradeNo(outTradeNo);

            BeanUtils.copyProperties(scheduleOrderVo, orderInfo);
            orderInfo.setScheduleId(scheduleOrderVo.getHosScheduleId());

            orderInfo.setPatientId(patient.getId());
            orderInfo.setPatientName(patient.getName());
            orderInfo.setPatientPhone(patient.getPhone());

            JSONObject data = response.getJSONObject("data");
            String fetchTime = data.getString("fetchTime");
            String fetchAddress = data.getString("fetchAddress");
            String hosRecordId = data.getString("hosRecordId");
            Integer number = data.getInteger("number");

            orderInfo.setHosRecordId(hosRecordId);
            orderInfo.setNumber(number);
            orderInfo.setFetchTime(fetchTime);
            orderInfo.setFetchAddress(fetchAddress);
            orderInfo.setOrderStatus(OrderStatusEnum.UNPAID.getStatus());
            baseMapper.insert(orderInfo);
            Integer availableNumber = data.getInteger("availableNumber");

            //3.2.2.跟新平台上医院的剩余可预约数
            OrderMqVo orderMqVo = new OrderMqVo();
            orderMqVo.setScheduleId(scheduleId); //设置排班id
            orderMqVo.setAvailableNumber(-1); //设置剩余可预约数
            MsmVo msmVo = new MsmVo();
            msmVo.setPhone(patient.getPhone());//设置就诊人的手机号
            msmVo.setTemplateCode("SMS_205402620"); //设置模版id

            Map<String,Object> map = new HashMap<String,Object>();
            map.put("number",323);
            msmVo.setParam(map);
            orderMqVo.setMsmVo(msmVo); //将所有信息封装到orderMqVo中
            rabbitTemplate.convertAndSend(MessageQueueContant.EXCHANGE_ORDER,MessageQueueContant.ROUTING_KEY_ORDER,orderMqVo);
            //3.2.3给就诊人发短信提示预约成功
            //3.1第三方医院不同意,抛出异常
        }else {
            throw new YYGHException(20001, "挂号失败");
        }
        //把订单id返回
        return orderInfo.getId();
    }

    //带查询条件的分页
    @Override
    public Page<OrderInfo> getOrderPage(Integer pageNum, Integer pageSize, OrderQueryVo orderQueryVo) {
        Page<OrderInfo> page = new Page<OrderInfo>(pageNum,pageSize);
        QueryWrapper<OrderInfo> wrapper = new QueryWrapper<OrderInfo>();
        //orderQueryVo获取条件值
        String name = orderQueryVo.getKeyword(); //医院名称
        Long patientId = orderQueryVo.getPatientId(); //就诊人名称
        String orderStatus = orderQueryVo.getOrderStatus(); //订单状态
        String reserveDate = orderQueryVo.getReserveDate();//安排时间
        String createTimeBegin = orderQueryVo.getCreateTimeBegin();
        String createTimeEnd = orderQueryVo.getCreateTimeEnd();

        wrapper.eq("user_id",orderQueryVo.getUserId());
        //对条件进行非空判断
        if(!StringUtils.isEmpty(name)) {
            wrapper.like("hosname",name);
        }
        if(!StringUtils.isEmpty(patientId)) {
            wrapper.eq("patient_id",patientId);
        }
        if(!StringUtils.isEmpty(orderStatus)) {
            wrapper.eq("order_status",orderStatus);
        }
        if(!StringUtils.isEmpty(reserveDate)) {
            wrapper.ge("reserve_date",reserveDate);
        }
        if(!StringUtils.isEmpty(createTimeBegin)) {
            wrapper.ge("create_time",createTimeBegin);
        }
        if(!StringUtils.isEmpty(createTimeEnd)) {
            wrapper.le("create_time",createTimeEnd);
        }
        Page<OrderInfo> orderInfoPage = baseMapper.selectPage(page, wrapper);
        for(OrderInfo record:orderInfoPage.getRecords()){
            record.getParam().put("orderStatusString", OrderStatusEnum.getStatusNameByStatus(record.getOrderStatus()));
        }
        return orderInfoPage;
    }

    @Override
    public OrderInfo getOrderInfo(Long orderId) {
        //根据订单id获取订单信息
        OrderInfo orderInfo = baseMapper.selectById(orderId);
        orderInfo.getParam().put("orderStatusString",OrderStatusEnum.getStatusNameByStatus(orderInfo.getOrderStatus()));
        return orderInfo;
    }
}